const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
const path = require('path')

module.exports = {
  publicPath: './',
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        ws: true,
        secure: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  chainWebpack: config => {
    config.resolve.alias // 为指定目录设置全局别名
      .set('@', path.join(__dirname, 'src'))
      .set('@public', path.join(__dirname, 'public'))
      .set('@router', path.join(__dirname, 'src/router'))
      .set('@store', path.join(__dirname, 'src/store'))
      .set('@utils', path.join(__dirname, 'src/utils'))

    const oneOfsMap = config.module.rule('less').oneOfs.store

    oneOfsMap.forEach(item => {
      item
        .use('style-resources-loader')
        .loader('style-resources-loader')
        .options({
          patterns: 'src/style/var.less'
        })
        .end()
    })

    config.module.rule('svg').exclude.add(path.join(__dirname, 'src/assets/icons')).end()
    config.module
      .rule('svg-sprite-loader')
      .test(/\.svg$/)
      .include.add(path.join(__dirname, 'src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  },
  configureWebpack: config => {
    config.output = {
      path: path.resolve(__dirname, 'dist'),
      filename: `js/[name].[hash].js`,
      publicPath: '',
      chunkFilename: `js/[name].[hash].js`
    }
    config.optimization = {
      splitChunks: {
        maxInitialRequests: 3,
        maxAsyncRequests: 5,
        cacheGroups: {
          vendors: {
            chunks: 'all',
            name: 'vendors',
            test: /(vue|vue-router|vuex|nprogress)/,
            priority: 100
          },
          async: {
            chunks: 'async',
            name: 'async-common',
            priority: 90
          },
          common: {
            chunks: 'all',
            name: 'common',
            priority: 80
          }
        }
      },
      runtimeChunk: {
        name: 'single'
      }
    }

    config.plugins = [
      ...config.plugins,
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ]
  }
}
